import { Body, Get, Inject, Post, Provide, Param } from '@midwayjs/core';
import { UserCollectService } from '../../service/collect';
import { BaseController, CoolController } from '@cool-midway/core';
import { UserCollectEntity } from '../../entity/collect';
import { GoodsInfoEntity } from '../../../goods/entity/info';

@Provide()
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: UserCollectEntity,
  service: UserCollectService,
  insertParam: ctx => {
    return {
      userId: ctx.user.id,
    };
  },
  listQueryOp: {
    select: ['a.userId', 'b.*'],
    where: async ctx => {
      return [['userId =:userId', { userId: ctx.user.id }]];
    },
    addOrderBy: {
      isDefault: 'DESC',
    },
    join: [
      {
        entity: GoodsInfoEntity,
        alias: 'b',
        condition: 'a.goodsId = b.id',
      },
    ],
  },  
  pageQueryOp: {
    select: ['a.userId', 'b.*'],
    where: async ctx => {
      return [['userId =:userId', { userId: ctx.user.id }]];
    },
    join: [
      {
        entity: GoodsInfoEntity,
        alias: 'b',
        condition: 'a.goodsId = b.id',
      },
    ],
  },
})

export class UserCollectController extends BaseController {
    @Inject()
    userCollectService: UserCollectService;

    @Inject()
    ctx;

    @Post('/toggle')
    async toggle(@Body('goodsId') goodsId: number) {
        return this.ok(await this.userCollectService.toggleCollect(this.ctx.user.id, goodsId));
    }

    @Get('/collect')
    async getUserCollects() {
        return this.ok(await this.userCollectService.getUserCollects(this.ctx.user.id));
    }

    @Get('/detail/:goodsId')
    async getUserCollectDetail(@Param('goodsId') goodsId: number) {
        return this.ok(await this.userCollectService.getUserCollectDetail(this.ctx.user.id, goodsId));
    }
} 